import React, { useState, useEffect } from "react";
import Constants from "expo-constants";
import {
  Button,
  Text,
  TextInput,
  View,
  ScrollView,
  Pressable,
  StyleSheet,
  Image,
  FlatList,
  KeyboardAvoidingView,
  Keyboard,
  Platform,
  TouchableWithoutFeedback,
} from "react-native";
import { Picker } from "@react-native-picker/picker";
import Icon from "react-native-vector-icons/FontAwesome";
import Ionicons from "react-native-vector-icons/Ionicons";
import Icon1 from "react-native-vector-icons/FontAwesome5";
import { useNavigation } from "@react-navigation/native";
import * as ImagePicker from "expo-image-picker";
import * as FileSystem from "expo-file-system";
import axios from 'axios';
import AsyncStorage from "@react-native-async-storage/async-storage";
import CommentInput from "../index/CommentInput";
import Toast from 'react-native-toast-message';
const myImage = require("../assets/guide.png");
const leftbutton = require("../assets/leftbutton.png");
const rightbutton = require("../assets/rightbutton.png");
const ActivityTypes = [
  "自习",
  "电影",
  "聚餐",
  "拼车",
  "拼单",
  "游戏",
  "运动",
  "旅行",
  "其他",
];

const ActivityDetail = ({ route }) => {
  const navigation = useNavigation();
  const [selectedActivity, setSelectedActivity] = useState(ActivityTypes[0]);
  const [postText, setPostText] = useState("");
  const [image, setImage] = useState(null);
  const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
  const [id, setId] = useState(route.params.id || '');
  const [userInfo, setUserInfo] = useState({});
  const [time, setTime] = useState(0);
  const [mark, setMarked] = useState('');
  const [images,setImages] = useState([]);
  const [activity, setActivity] = useState({});
  const [comments, setComments] = useState([
    { id: '1', username: '评论者A', content: '这是评论内容A...', userImg: 'https://placekitten.com/200/200' },
  ]);
  const handlePost = () => {
    console.log("发布的活动类型: ", selectedActivity);
    console.log("发布的正文: ", postText);
  };
  const convertImageToBase64 = async (imageUri) => {
    try {
        const base64Data = await FileSystem.readAsStringAsync(imageUri, {
            encoding: FileSystem.EncodingType.Base64,
        });
        return base64Data;
    } catch (error) {
        console.error(error);
    }
}
  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 4],
      quality: 1,
    });

    console.log(result.assets[0]);

    // 检查图片是否是Base64格式
    if (!/^data:image\/[a-zA-Z]*;base64,/.test(result.assets[0].uri)) {
      convertImageToBase64(result.assets[0].uri)
        .then((base64Data) => {
          console.log("Image (base64): ", base64Data);
          setImage("data:image/jpg;base64," + base64Data);
        })
        .catch((err) => {
          console.error("Error converting image to base64", err);
        });
    } else {
      setImage(result.assets[0].uri);
    }
  };
  const getFormattedCurrentTime = () => {
    const now = new Date(); // 获取当前时间
    const year = now.getFullYear(); // 年
    const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月，月份是从0开始计数的
    const day = now.getDate().toString().padStart(2, '0'); // 日
    const hours = now.getHours().toString().padStart(2, '0'); // 时
    const minutes = now.getMinutes().toString().padStart(2, '0'); // 分
    const seconds = now.getSeconds().toString().padStart(2, '0'); // 秒

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  const handleMarked = () => {
    if(activity.username === userInfo.username){
      Toast.show({
        type: 'error',
        text1: '自己不能退出攒局喔~',
      });
      return;
    }
    if (mark) {
      setMarked(false);
      axios.post('http://47.111.227.58:3000/dynamic/updateActivityMarkUsers', {
        postId: id,
        userId: userInfo.username
      }).then(res => {
        console.log(res.data);
        getActivityUser()
      });
    } else {
      setMarked(true);
      axios.post('http://47.111.227.58:3000/dynamic/updateActivityMarkUsers', {
        postId: id,
        userId: userInfo.username
      }).then(res => {
        console.log(res.data);
        getActivityUser()
      });
    }
  };
  const getActivityUser = () => {
    axios.get('http://47.111.227.58:3000/dynamic/getPostActivityUsers', {
      params: {
        id: id
      }
    }).then(res => {
      // console.log(res.data)
      let newImages = res.data.results;
      let newImage = { username: activity.username, imgUrl: activity.userImg }
      newImages.push(newImage);
      setImages(res.data.results)
      // setUserInfo(res.data.data)
    })
  }
  const addNewComment = (comment) => {
    const currentTime = getFormattedCurrentTime();
    setTime(currentTime)
    if (comment != '') {
      axios.post('http://47.111.227.58:3000/dynamic/addcomments', {
        data: {
          ac_id: id,
          username: userInfo.username,
          phone: userInfo.phone,
          userImg: userInfo.imgUrl,
          content: comment,
          uploadTime: time
        }
      }).then(res => {
        console.log(res.data)
        axios.post('http://47.111.227.58:3000/dynamic/updataIdCharacter', {
          data: {
            character: Number(userInfo.characters) + 1,
            id: userInfo.id
          }
        }).then(res => {
          // console.log(res.data);
          userInfo.characters = Number(userInfo.characters) + 1
          AsyncStorage.setItem('userInfo', JSON.stringify(userInfo));
        });
      })
    }
    const newComment = {
      ac_id: id,
      username: userInfo.username,
      phone: userInfo.phone,
      userImg: userInfo.imgUrl,
      content: comment,
      uploadTime: time
    };
    setComments([...comments, newComment]);
  };
  const getCommentList = async () => {
    axios.post('http://47.111.227.58:3000/dynamic/getActivityComments', {
      data: {
        ac_id: id
      },
    })
      .then((res) => {
        // console.log(res.data);
        setComments(res.data.data)
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  };
  const pickVideo = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Videos,
      allowsEditing: false,
      quality: 1, // 视频选择不支持编辑，此选项可以设置视频的质量
    });
    if (!result.canceled) {
      const video = result.assets[0];
      console.log(video);
      // 视频的本地 URI 在 video.uri
    }
  };
  const deleteButton = () => {
    setImage(null);
  };
  const getActivityList = async () => {
    axios.post('http://47.111.227.58:3000/dynamic/searchActivity', {
      data: {
        id: id
      },
    })
      .then((res) => {
        // console.log(res.data[0]);
        setActivity(res.data[0])
        const initialMarked = res.data[0].markUsers?.split(',').includes(userInfo.username);
        setMarked(initialMarked)
        // setComments(response.data);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  };
  // 点击空白处隐藏键盘和发送按钮的函数
  const handleHideKeyboard = () => {
    setIsKeyboardVisible(false);
    Keyboard.dismiss();
  };
  useEffect(() => {
    (async () => {
      console.log('postId:', id);
      if (route.params.id) {
        setId(route.params.id)
      }
      const userinfo = await AsyncStorage.getItem('userInfo');
      if (userinfo) {
        setUserInfo(JSON.parse(userinfo));
      }
      
      // 监听键盘显示和隐藏事件
      const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
        setIsKeyboardVisible(true);
      });
      const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
        setIsKeyboardVisible(true);
      });

      // 清理监听器
      return () => {
        keyboardDidShowListener.remove();
        keyboardDidHideListener.remove();
      };
    })();
  }, []);
  useEffect(() => {
    if (userInfo.username) {
      getActivityList();
      getCommentList();
      
    }
  }, [userInfo]);
  useEffect(() => {
    if (activity) {
      getActivityUser()
    }
  }, [activity]);
  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === "ios" ? "padding" : "height"}
      keyboardVerticalOffset={Platform.OS === "ios" ? 90 : 0}
    >
      <TouchableWithoutFeedback onPress={handleHideKeyboard}>
        <ScrollView >
          <View >
            <View style={styles.header}>
              <Text style={styles.headerText}>局内成员</Text>
            </View>
            <View style={styles.content}>
              <View style={styles.contentTop}>
                {images.map((imageSrc, index) => (
                  <View key={index} style={styles.contentTopContainer}>
                    <Image
                      key={index} // 为每个元素添加一个唯一的 key
                      style={styles.contentTopavatar}
                      source={{uri: imageSrc.imgUrl}} // 使用对象形式传递 source 属性
                    />
                    <Text style={styles.contentTopText}>{imageSrc.username}</Text>
                  </View>
                ))}
              </View>
            </View>
            <View style={styles.header}>
              <Text style={styles.headerText}>局情</Text>
            </View>
            <View style={styles.MiddleContent}>
              <View style={styles.Middleheader}>
                <Image
                  style={styles.avatar}
                  source={{ uri: activity.userImg }}
                />
                <Text style={styles.username}>{activity.username}</Text>
                <Text style={styles.uploadTime}>{activity.uploadTime}</Text>
              </View>
              <Text style={styles.postContent}>{activity.desc}</Text>
              {activity.imgUrl && (
                <Image
                  source={{ uri: activity.imgUrl }}
                  style={styles.messageImage} />
              )}
            </View>
            <Pressable onPress={handleMarked} style={styles.BottomButton}>
              <Text style={styles.BottomButtonText}>我想去</Text>
            </Pressable>
            <View style={styles.header}>
              <Text style={styles.headerText}>公开讨论</Text>
            </View>
            <View style={styles.BottomContent}>
              {comments.map((comment) => (
                <View key={comment.id} style={styles.commentItem}>
                  <Image
                    style={styles.commentAvatar}
                    source={{uri: comment.userImg}}
                  />
                  <View style={styles.commentContent}>
                    <Text style={styles.commentUsername}>
                      {comment.username}
                    </Text>
                    <Text>{comment.content}</Text>
                  </View>
                  {/* <Pressable style={styles.likeWrapper}>
                    <Icon name="thumbs-o-up" size={18} color="#b8b8b8" />
                  </Pressable> */}
                  {/* {comment.username === userInfo.username && (
                            <Pressable onPress={() => handleDeleteCommit(comment.id)} style={styles.likeButton}>
                                <Text>删除</Text>
                            </Pressable>
                        )} */}
                </View>
              ))}
            </View>
          </View>
        </ScrollView>
      </TouchableWithoutFeedback>
      <CommentInput
        onCommentSubmit={addNewComment}
        isKeyboardVisible={isKeyboardVisible}
        setIsKeyboardVisible={setIsKeyboardVisible}
        style={styles.commentInput}
      />
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#FAD874",
    width: "100%",
    height: "100%",
    paddingTop: Constants.statusBarHeight,
  },
  header: {
    flexDirection: "row",
    padding: 5,
    paddingLeft: 10,
  },
  headerText: {
    fontSize: 16,
    color: "#000",
    fontWeight: "bold",
    marginLeft: 10,
  },
  Tags: {
    width: "100%",
    height: "15%",
    // marginTop: -20,
  },
  TopTags: {
    flexDirection: "row",
    width: "100%",
    height: "50%",
  },
  BottomTags: {
    flexDirection: "row",
    width: "100%",
    height: "50%",
    marginTop: -10,
  },
  Tag: {
    flexDirection: "row",
    width: "18%",
    backgroundColor: "#FFFDF1",
    borderBlockColor: "#000",
    borderWidth: 2,
    borderRadius: 5,
    boxShadow: '2px 2px 2px rgba(0, 0, 0, 1)',
    margin: 10,
    marginLeft: 6,
    marginRight: 0,
    display: "flex",
    alignItems: "center",
    // padding: 5,
  },
  TagColor1: {
    width: "10%",
    height: "100%",
    backgroundColor: "#4094F7",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor2: {
    width: "10%",
    height: "100%",
    backgroundColor: "#FE6386",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor3: {
    width: "10%",
    height: "100%",
    backgroundColor: "#F6A514",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor4: {
    width: "10%",
    height: "100%",
    backgroundColor: "#FD7C42",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor5: {
    width: "10%",
    height: "100%",
    backgroundColor: "#FE655F",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor6: {
    width: "10%",
    height: "100%",
    backgroundColor: "#00B773",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor7: {
    width: "10%",
    height: "100%",
    backgroundColor: "#B758FD",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor8: {
    width: "10%",
    height: "100%",
    backgroundColor: "#03BBD1",
    display: "flex",
    alignItems: "flex-start",
  },
  TagColor9: {
    width: "10%",
    height: "100%",
    backgroundColor: "#4CA4FD",
    display: "flex",
    alignItems: "flex-start",
  },
  TagIcon: {
    color: "#9B999C",
    display: "flex",
  },
  TagTitle: {
    fontSize: 14,
    fontWeight: "bold",
    color: "#9B999C",
    display: "flex",
  },
  TagContent: {
    fontSize: 14,
    fontWeight: "bold",
    color: "#24201D",
    display: "flex",
    marginLeft: 12,
  },
  content: {
    height: 100,
    backgroundColor: "#FFFDF1",
    borderBlockColor: "#000",
    borderWidth: 2,
    borderRadius: 5,
    boxShadow: '2px 2px 2px rgba(0, 0, 0, 1)',
    marginLeft: 10,
    marginRight: 10,
  },
  contentTop: {
    height: 80,
    flexDirection: "row",
  },
  contentTopContainer: {
    display: 'flex',
    flexDirection: "column",
    overflow: 'hidden',
    width: '20%',
    flexWrap: 'nowrap',
    alignItems: 'center',
  },
  contentTopText: {
    display: 'flex',
    flexDirection: 'row',
    overflow: 'hidden',
    // width: 10,
    fontSize: 14,
    // fontWeight: "bold",
    paddingLeft: 10,
  },
  contentBottom: {
    height: 75,
    backgroundColor: "#FFFDF1",
    flexDirection: "row",
    borderBottomLeftRadius: 5,
    borderBottomRightRadius: 5,
  },
  contentBottomimage: {
    width: 70,
    height: 70,
    backgroundColor: "#F4F4F4",
    marginLeft: 10,
  },
  contentBottomvideo: {
    width: 70,
    height: 70,
    backgroundColor: "#F4F4F4",
    marginLeft: 10,
  },
  contentBottomIcon: {
    position: "absolute",
    top: "25%",
    left: "34%",
  },
  contentBottomText: {
    position: "absolute",
    top: "55%",
    left: "21%",
    color: "#BABABA",
    fontSize: 10,
  },
  input: {
    height: 175,
    width: "100%",
    padding: 10,
  },
  contentTopRight: {
    height: 175,
    width: "20%",
    flexDirection: "column",
  },
  contentTopRightIcon: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F4F4F4",
    margin: 25,
    marginLeft: 30,
    marginRight: 10,
  },
  contentTopRightIconItem: {
    margin: 5,
  },
  contentTopavatar: {
    width: 40,
    height: 40,
    borderRadius: 25,
    margin: 10,
    marginBottom: 0,
    overflow: "scroll",
  },
  MiddleContent: {
    display: "flex",
    flexDirection: "column",
    // width: '90%',
    height: 150,
    // justifyContent: 'space-between',
    // alignItems: 'center',
    borderRadius: 5,
    backgroundColor: "#FFFDF1",
    borderBlockColor: "#000",
    borderWidth: 2,
    boxShadow: '2px 2px 2px rgba(0, 0, 0, 1)',
    marginLeft: 10,
    marginRight: 10,
  },
  Middleheader: {
    display: "flex",
    flexDirection: "row",
    width: "90%",
    alignItems: "center",
    marginLeft: 10,
    marginRight: 10,
    marginTop: 10,
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 25,
  },
  username: {
    fontWeight: "bold",
    fontSize: 16,
    marginLeft: 10,
  },
  uploadTime: {
    // fontWeight: 'bold',
    color: "#b8b8b8",
    fontSize: 12,
    marginLeft: "auto",
    marginRight: 0,
  },
  postContent: {
    display: "flex",
    marginTop: 8,
    marginLeft: 10,
    fontSize: 14,
    fontWeight: "bold",
  },
  messageImage: {
    width: "30%",
    height: "45%",
    borderRadius: 5,
    borderWidth: 1,
    borderColor: "#ddd",
    marginBottom: 10,
    marginLeft: 10,
  },
  BottomContent: {
    display: "flex",
    flexDirection: "column",
    // width: '90%',
    // height: '10%',
    justifyContent: "space-between",
    alignItems: "center",
    borderRadius: 5,
    backgroundColor: "#FFFDF1",
    borderBlockColor: "#000",
    borderWidth: 2,
    boxShadow: '2px 2px 2px rgba(0, 0, 0, 1)',
    marginLeft: 10,
    marginRight: 10,
  },
  BottomContentLeft: {
    display: "flex",
    flexDirection: "row",
  },
  BottomContentRight: {
    display: "flex",
    width: "20%",
    marginRight: 10,
  },
  BottomContentInput: {
    display: "flex",
    width: "100%",
  },
  BottomButton: {
    backgroundColor: "#FD6A61",
    color: "#fff",
    padding: 10,
    marginRight: 15,
    marginLeft: 15,
    borderRadius: 20,
    marginTop: 10,
    alignItems: "center",
    justifyContent: "center",
  },
  BottomButtonText: {
    color: "#fff",
    fontWeight: "bold",
    fontSize: 14,
  },
  likeButton: {
    flexDirection: "row",
    alignItems: "center",
  },
  commentsContainer: {
    backgroundColor: "#f0f0f0",
    paddingVertical: 10,
  },
  commentsHeader: {
    fontSize: 14,
    marginLeft: 15,
    marginBottom: 10,
  },
  commentItem: {
    width: "100%",
    flexDirection: "row",
    padding: 15,
    backgroundColor: "#FFFDF1",
    borderBottomWidth: 1,
    borderBottomColor: "#ececec",
    alignItems: "center",
  },
  commentAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
  },
  commentUsername: {
    fontWeight: "bold",
  },
  commentContent: {
    flex: 1,
    marginLeft: 10,
  },
  likeWrapper: {
    padding: 8,
  },
  openCommentBoxButton: {
    padding: 10,
    borderTopWidth: 1,
    borderTopColor: "#ddd",
    alignItems: "center",
  },
  openCommentBoxText: {
    color: "#007bff",
  },
  commentBox: {
    padding: 15,
    borderTopWidth: 1,
    borderTopColor: "#ddd",
  },
  commentInput: {
    position: "absolute",
    bottom: 0,
    width: "100%",
  },
});

export default ActivityDetail;
